#import "SearchMapViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <Masonry/Masonry.h>
#import "PoiModel.h"
#import "MapSharePoiTableViewCell.h"
#import "Location.h"
#import <YYKeyboardManager/YYKeyboardManager.h>
#import "LocationUtil.h"

@interface SearchMapViewController ()
<UITableViewDelegate,
UITableViewDataSource,
MAMapViewDelegate,
UITextFieldDelegate,
YYKeyboardObserver,
AMapSearchDelegate>

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITableView *searchTableView;
@property (nonatomic, strong) NSArray<PoiModel *> *searchArray;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, strong) NSArray<PoiModel *> *dataArray;
@property (nonatomic, strong) UIButton *sendButton;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIButton *closeBtn;
@property (nonatomic, strong) UIView *navView;
@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) AMapPOI *selectedPoi;
@property (nonatomic, strong) UIImageView *annotationView;
@property (nonatomic, assign) BOOL hasUserLocation;
@property (nonatomic, assign) BOOL isSearch;
@property (nonatomic, assign) CGFloat statusHeight;
/// 是否需要重新 poi 搜索
@property (nonatomic, assign) BOOL isNeededPOISearch;
@property (nonatomic, strong) void(^sendAction)(id<DGLBSLocation> _Nullable);

@end

@implementation SearchMapViewController

- (instancetype)initWithBlock:(void (^)(id<DGLBSLocation> _Nullable))block {
    if (self = [super init]) {
        self.sendAction = block;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 状态栏高度
    self.statusHeight = [[UIApplication sharedApplication] statusBarFrame].size.height;
    
    [[YYKeyboardManager defaultManager] addObserver:self];
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
    [self createSubViews];
    
    [self.locationManager requestLocationWithReGeocode: YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
        request.location = [AMapGeoPoint locationWithLatitude: location.coordinate.latitude longitude: location.coordinate.longitude];
        self.isSearch = false;
        [self.search AMapPOIAroundSearch:request];
    }];
}

- (void)createSubViews{
    [self.view addSubview:self.mapView];
    [self.mapView addSubview:self.annotationView];
    // 自定义导航栏
    self.navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, _statusHeight + 44)];
    _navView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_navView];
    UILabel *line1 = [[UILabel alloc] init];
    line1.backgroundColor = [UIColor colorWithRed:233/255.0 green:233/255.0 blue:233/255.0 alpha:1.0];
    [_navView addSubview:line1];
    // 自定义导航标题
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.font = [UIFont systemFontOfSize:17 weight:550];
    titleLbl.textColor = [UIColor blackColor];
    titleLbl.text = @"位置";
    [_navView addSubview:titleLbl];
    
    // 自定义搜索视图
    self.searchView = [[UIView alloc] init];
    _searchView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_searchView];
    UILabel *line2 = [[UILabel alloc] init];
    line2.backgroundColor = [UIColor colorWithRed:233/255.0 green:233/255.0 blue:233/255.0 alpha:1.0];
    [_searchView addSubview:line2];
    self.textField = [[UITextField alloc] init];
    _textField.placeholder = @"搜索地点";
    _textField.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0];
    _textField.textColor = [UIColor blackColor];
    _textField.layer.masksToBounds = YES;
    _textField.layer.cornerRadius = 6.0;
    _textField.keyboardType = UIKeyboardTypeWebSearch;
    UIView *leftView = [[UIView alloc] init];
    _textField.leftView = leftView;
    _textField.leftViewMode = UITextFieldViewModeAlways;
    UIImageView *imgView = [[UIImageView alloc] init];
    NSString *strResourcesBundle = [[NSBundle mainBundle] pathForResource:@"DTKMapBundle" ofType:@"bundle"];
    NSString *strC = [[NSBundle bundleWithPath:strResourcesBundle] pathForResource:@"sousuo" ofType:@"png"];
    UIImage *imgC = [UIImage imageWithContentsOfFile:strC];
    imgView.image = imgC;
    [leftView addSubview:imgView];
    [_textField addTarget:self action:@selector(textFiledDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_searchView addSubview:_textField];
    
    // 取消搜索
    self.closeBtn = [UIButton buttonWithType: UIButtonTypeCustom];
    [_closeBtn setTitle:@"取消" forState:UIControlStateNormal];
    _closeBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [_closeBtn setTitleColor:[UIColor colorWithRed:0 green:137/255.0 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
    [_closeBtn addTarget:self action:@selector(closeBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [_searchView addSubview:_closeBtn];
    _closeBtn.hidden = YES;
    
    [leftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_textField);
        make.top.equalTo(_textField).offset(5);
        make.size.mas_equalTo(CGSizeMake(35, 22));
    }];
    [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftView).mas_offset(@5);
        make.centerY.equalTo(leftView);
        make.size.mas_equalTo(CGSizeMake(22, 22));
    }];
    
    [self.view addSubview:self.tableView];
    [_navView addSubview:self.sendButton];
    [_navView addSubview:self.cancelButton];
    
    [_sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_navView).offset(-9);
        make.right.equalTo(_navView).offset(-20);
        make.width.equalTo(@40);
        make.height.equalTo(@25);
    }];
    
    [_cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_navView).offset(-9);
        make.left.equalTo(_navView).offset(20);
        make.width.equalTo(@40);
        make.height.equalTo(@26);
    }];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_navView);
        make.centerY.equalTo(_cancelButton);
    }];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_navView);
        make.height.mas_equalTo(@1);
        make.bottom.equalTo(_navView).offset(-1);
    }];
    
    [_mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(_navView.mas_bottom);
        make.height.mas_equalTo(330);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(_mapView.mas_bottom);
    }];
    
    [_annotationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mapView);
        make.centerY.equalTo(self.mapView).offset(12);
        make.width.height.equalTo(@35);
    }];
    
    [_searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(_navView.mas_bottom);
        make.height.equalTo(@44);
    }];
    [_textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_searchView).offset(10);
        make.right.equalTo(_searchView).offset(-10);
        make.centerY.equalTo(_searchView);
        make.height.equalTo(@32);
    }];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_searchView);
        make.height.mas_equalTo(@1);
        make.bottom.equalTo(_searchView).offset(-1);
    }];
    [_closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_searchView);
        make.right.equalTo(_searchView).offset(-10);
        make.width.equalTo(@40);
        make.height.equalTo(@26);
    }];
    
    // 搜索tableView
    self.searchTableView = [[UITableView alloc] init];
    _searchTableView.delegate = self;
    _searchTableView.dataSource = self;
    _searchTableView.rowHeight = 60;
    [_searchTableView registerClass:[MapSharePoiTableViewCell self] forCellReuseIdentifier:@"PoiTableViewCell1"];
    [self.view addSubview:_searchTableView];
    _searchTableView.hidden = YES;
    [_searchTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(_searchView.mas_bottom);
    }];
}

- (void)sendClick:(UIButton *)sender {
//    AMapLocationManager *locationManager = [LocationUtil shareInstance].locationManager;
//    locationManager.distanceFilter = kCLDistanceFilterNone;
//    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
//    locationManager.pausesLocationUpdatesAutomatically = NO;
//    [locationManager requestLocationWithReGeocode: YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
//        NSLog(@"定位：%@", location);
//    }];
    if (!self.selectedPoi) {
        return;
    }
    Location *location = [Location new];

    location.location = [[CLLocation alloc] initWithLatitude:self.selectedPoi.location.latitude longitude:self.selectedPoi.location.longitude];
    location.name = self.selectedPoi.name;
    location.address = self.selectedPoi.address;
    location.province = self.selectedPoi.province;
    location.city = self.selectedPoi.city;
    location.district = self.selectedPoi.district;
    location.dateTime = [NSDate date];
    location.snapshotImage = [self.mapView takeSnapshotInRect:CGRectMake(0, _statusHeight + 44, self.view.frame.size.width, 330)];
    if (self.sendAction) {
        self.sendAction(location);
//        [self.navigationController popViewControllerAnimated:YES];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)cancelClick:(UIButton *)sender {
//    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 取消搜索
- (void)closeBtnAction{
    [self.view endEditing:YES];
    CGRect frame = self.navView.frame;
    frame.origin.y = 0;
    self.navView.frame = frame;
    [self.textField mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.searchView).offset(-10);
    }];
    _closeBtn.hidden = YES;
    _navView.hidden = NO;
    _searchTableView.hidden = YES;
    _textField.text = nil;
}

- (void)keyboardChangedWithTransition:(YYKeyboardTransition)transition {
    CGFloat height = transition.toFrame.size.height;
    NSTimeInterval animationDuration = transition.animationDuration;
    if (transition.toVisible) {
        [UIView animateWithDuration:animationDuration animations:^{
            CGRect frame = self.navView.frame;
            frame.origin.y = -self.statusHeight - 25;
            self.navView.frame = frame;
        }];
        [self.textField mas_updateConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.searchView).offset(-60);
        }];
        _closeBtn.hidden = NO;
        _navView.hidden = YES;
        if (!_searchTableView.hidden) {
            [_searchTableView setContentInset:UIEdgeInsetsMake(0, 0, height, 0)];
        }
    } else {
        if (!_searchTableView.hidden) {
            [_searchTableView setContentInset:UIEdgeInsetsZero];
        }
    }
}

- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response {
    if (response.pois.count == 0) {
        return;
    }

    NSMutableArray *dataSource = [NSMutableArray array];
    for (int i = 0; i < response.pois.count; i++) {
        PoiModel *model = [PoiModel new];
        model.poi = response.pois[i];
        model.selected = false;
        [dataSource addObject:model];
    }
    if (!self.isSearch) {
        self.dataArray = [dataSource copy];
        self.dataArray.firstObject.selected = true;
        if (dataSource && dataSource.count > 0) {
            PoiModel *firstModel = dataSource[0];
            self.selectedPoi = firstModel.poi;
        }
        [self.tableView reloadData];
    } else {
        _searchArray = [dataSource copy];
        [_searchTableView reloadData];
    }
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    if (self.hasUserLocation) {
        return;
    }
    self.mapView.zoomLevel = 13.5;
    [mapView setCenterCoordinate: userLocation.coordinate animated: YES];
    self.hasUserLocation = true;
}

- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction {
    if (!wasUserAction) {
        return;
    }
    CLLocationCoordinate2D coordinate = [self.mapView convertPoint:self.mapView.center toCoordinateFromView:self.mapView];
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude: coordinate.latitude longitude: coordinate.longitude];
    self.isSearch = false;
    [self.search AMapPOIAroundSearch:request];
}

- (void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate {
    [self.view endEditing:YES];
}

- (void)textFiledDidChange:(UITextField *)textField {
    UITextField *inputTextFiled = textField;
    UITextRange *selectedRange = inputTextFiled.markedTextRange;
    UITextPosition *position = [inputTextFiled positionFromPosition:selectedRange.start offset:0];
    if (!position) {
        if (textField.text.length > 0) {
            self.isSearch = true;
            AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
            request.keywords = inputTextFiled.text;
            [self.search AMapPOIKeywordsSearch:request];
            _searchTableView.hidden = NO;
        } else {
            _searchTableView.hidden = YES;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == _searchTableView) {
        return _searchArray.count;
    }
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _searchTableView) {
        static NSString *identifier1 = @"PoiTableViewCell1";
        MapSharePoiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier1];
        [cell configure:_searchArray[indexPath.row]];
        
        return cell;
    }
    static NSString *identifier = @"PoiTableViewCell";
    MapSharePoiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    [cell configure:self.dataArray[indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _searchTableView) {
        PoiModel *model = _searchArray[indexPath.row];
        [self.mapView setCenterCoordinate: CLLocationCoordinate2DMake(model.poi.location.latitude, model.poi.location.longitude) animated: YES];
        _isSearch = NO;
        AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
        request.keywords = model.poi.name;
        [self.search AMapPOIKeywordsSearch:request];
        
        [self closeBtnAction];
        return;
    }
    for (PoiModel *model in self.dataArray) {
        model.selected = false;
    }
    PoiModel *model = self.dataArray[indexPath.row];
    model.selected = true;
    self.selectedPoi = model.poi;
    [self.tableView reloadData];
    [self.mapView setCenterCoordinate: CLLocationCoordinate2DMake(model.poi.location.latitude, model.poi.location.longitude) animated: YES];
}


- (MAMapView *)mapView {
    if (!_mapView) {
        _mapView = [[MAMapView alloc] init];
        _mapView.showsUserLocation = YES;
        _mapView.delegate = self;
        _mapView.userTrackingMode = MAUserTrackingModeNone;
        _mapView.distanceFilter = kCLLocationAccuracyHundredMeters;
    }
    return _mapView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 60;
        [_tableView registerClass:[MapSharePoiTableViewCell self] forCellReuseIdentifier:@"PoiTableViewCell"];
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    }
    return _tableView;
}

- (AMapLocationManager *)locationManager {
    if (!_locationManager) {
        //初始化实例
        _locationManager = [[AMapLocationManager alloc] init];
        //设置距离过滤参数
        _locationManager.distanceFilter = kCLDistanceFilterNone;
        //设置预期精度参数
        _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        //设置是否自动停止位置更新
        _locationManager.pausesLocationUpdatesAutomatically = NO;
    }
    return _locationManager;
}

- (UIImageView *)annotationView {
    if (!_annotationView) {
        _annotationView = [[UIImageView alloc] init];
//        _annotationView.image = [UIImage imageNamed:@"datouzhen"];
        NSString *strResourcesBundle = [[NSBundle mainBundle] pathForResource:@"DTKMapBundle" ofType:@"bundle"];
        NSString *strC = [[NSBundle bundleWithPath:strResourcesBundle] pathForResource:@"datouzhen" ofType:@"png"];
        UIImage *imgC = [UIImage imageWithContentsOfFile:strC];
        _annotationView.image = imgC;
    }
    return _annotationView;
}

- (UIButton *)sendButton {
    if (!_sendButton) {
        _sendButton = [UIButton buttonWithType: UIButtonTypeCustom];
        [_sendButton setTitle:@"发送" forState:UIControlStateNormal];
        [_sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_sendButton addTarget:self action:@selector(sendClick:) forControlEvents:UIControlEventTouchUpInside];
        _sendButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_sendButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    return _sendButton;
}

- (UIButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [UIButton buttonWithType: UIButtonTypeCustom];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelClick:) forControlEvents:UIControlEventTouchUpInside];
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    return _cancelButton;
}

@end
